package com.csaba.connector.otp;

import java.util.logging.Logger;

import com.csaba.connector.ServiceException;
import com.csaba.connector.otp.model.OTPRequestFactory;
import com.csaba.connector.otp.model.OTPSession;
import com.csaba.util.LoggerHelper;

public class TransactionPolling
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	public static final int POLL_LIMIT = 30;
	public static final int POLL_PERIOD = 1000;
	private static final String POLL_RESULT_FINISHED = "FINISHED";
	private static final String POLL_WAITING = "WAITING";

	private final OTPSession session;
	private final String URL;

	public TransactionPolling( final OTPSession session, final String URL )
	{
		this.session = session;
		this.URL = URL;
	}

	public boolean poll() throws ServiceException
	{
		int pollCount = 0;
		for ( String poll = POLL_WAITING; !POLL_RESULT_FINISHED.equals(poll) && pollCount < POLL_LIMIT; pollCount++ )
		{
			try
			{
				Thread.sleep(POLL_PERIOD);
			}
			catch ( final InterruptedException ex )
			{
				logger.finest("Sleep was interrupted.");
			}

			poll = session.doGet(OTPRequestFactory.HOMEBANK_REQUEST_URL_BASE + URL);
			logger.fine("Poll[" + pollCount + "]:" + poll);
		}

		return pollCount < POLL_LIMIT;

	}

	public static String parsePollTransaction( final String accountListRequest ) throws ServiceException
	{
		final int pos = accountListRequest.indexOf(OTPRequestFactory.REQUEST_POLL_TRANSACTION_ANSWER);
		if ( pos < 0 )
		{
			throw new ServiceException("Invalid account list request reply. No poll transaction is available.");
		}

		final int endPos = accountListRequest.indexOf("'", pos);
		if ( endPos < 0 )
		{
			throw new ServiceException("Invalid account list request reply. Unparsable poll transaction URL.");
		}

		return accountListRequest.substring(pos, endPos);
	}
}
